/*
 * @Author: yangzonglong
 * @Date: 2021-03-09 16:03:48
 * @version: v1.0.0
 * @Descripttion: 列
 * @LastEditors: Please set LastEditors
 * @LastEditTime: 2021-11-16 17:46:54
 * @Auditor:
 */
import React, { useMemo } from 'react';
import { Form, Button, } from 'antd';
import Icon from '../../icon/Icon';
import SortItem from './SortItem';
import styles from './style.module.scss';

const FormItem = Form.Item;

interface IProps {
  changeControlProps(v: any[]): void;
  columns: any[];
  dataSource: any[];
}

const Columns = ({ columns, changeControlProps, dataSource }: IProps) => {

  const _dataSource = useMemo(() => {
    return (dataSource || []).map((_, index) => ({ ..._, id: _.value }));
  }, [dataSource]);

  return (
    <>
      <FormItem label="数据排序">
        <ul className={styles.options}>
          {
            columns?.map((item, index) => <SortItem dataSource={_dataSource} originalIndex={index} item={item} remove={(index) => {
              changeControlProps(columns?.filter((item, i) => i !== index));
            }} changeKey={(value: any, index: number) => {
              changeControlProps(columns?.map((item, i) => (i === index ? { ...item, key: value } : item)));
            }} changeSort={(value: any, index: number) => {
              changeControlProps(columns?.map((item, i) => (i === index ? { ...item, sort: value } : item)));
            }} />)
          }
        </ul>
        <p style={columns?.length ? { margin: '8px 0 0 0' } : { margin: 0 }}></p>
        <Button className={styles.btnStyle} onClick={() => {
          changeControlProps?.(columns.concat({ key: '', sort: '' }));
        }
        } icon={<Icon icon="&#xe635;" />} block>
          添加新选项
        </Button>

      </FormItem>
    </>
  );
};

export default Columns;
